package sol.leetcode;

import def.TreeNode;

import java.util.*;

/**
 * Binary Tree Inorder Traversal
 */
public class Issue094 {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        List<TreeNode> visited = new ArrayList<TreeNode>();
        Stack<TreeNode> stk = new Stack<TreeNode>();
        if (root != null)
            stk.push(root);
        while (!stk.empty()) {
            TreeNode top = stk.peek();
            //如果有未被访问的左子树
            if (top.left != null && !visited.contains(top.left)) {
                stk.push(top.left);
            } else {
                stk.pop();
                res.add(top.val);
                visited.add(top);
                if (top.right != null)
                    stk.push(top.right);
            }
        }
        return res;

        //参考答案
        //List<Integer> res = new LinkedList<Integer>();
        //if (root == null) return res;
        //
        //Stack<TreeNode> stack = new Stack<TreeNode>();
        //TreeNode cur = root;
        //while (cur != null || !stack.isEmpty()) {
        //    while (cur != null) {// Travel to the left leaf
        //        stack.push(cur);
        //        cur = cur.left;
        //    }
        //    cur = stack.pop(); // Backtracking to higher level node A
        //    res.add(cur.val);  // Add the node to the result list
        //    cur = cur.right;   // Switch to A'right branch
        //}
        //return res;
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;

        System.out.println(new Issue094().inorderTraversal(null));
    }
}
